import { defineStore } from 'pinia';
import { ref } from 'vue';
import axios from 'axios'; // 假设已安装axios
// 设置axios的基础URL
axios.defaults.baseURL = 'https://www.you04.cn';

export const useLogStore = defineStore('log', () => {
    const token = ref(sessionStorage.getItem('token')|| localStorage.getItem('token'));
    const logs = ref([]);
    const pagination = ref({
        page: 1,
        pageSize: 10,
        total: 0
    });
    // 获取日志列表
    const getLogs = async (searchParams = {}) => {
        try {
            const response = await axios.get('/api/operation-logs', {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                },
                params: {
                    page: pagination.value.page,
                    size: pagination.value.pageSize,
                    ...searchParams
                }
            });
            const { items, totalCount, pageIndex, pageSize } = response.data.data;
            logs.value = items;
            pagination.value = {
                page: pageIndex,
                pageSize: pageSize,
                total: totalCount
            };
            return { logs: logs.value, pagination: pagination.value }
        } catch (error) {
            throw new Error(error.message || '获取日志失败');
        }
    };

    // 搜索日志（使用高级搜索接口）
    const searchLogs = async (searchForm, paginationParams = {}) => {
        try {
            const params = {
                pageIndex: paginationParams.page || pagination.value.page,
                pageSize: paginationParams.pageSize || pagination.value.pageSize
            };

            if (searchForm.username) params.username = searchForm.username;
            if (searchForm.action) params.action = searchForm.action;
            if (searchForm.module) params.resource = searchForm.module;
            if (searchForm.dateRange && searchForm.dateRange.length === 2) {
                params.startDate = searchForm.dateRange[0];
                params.endDate = searchForm.dateRange[1];
            }

            const response = await axios.get('/api/operation-logs/search', {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                },
                params
            });

            const { items, totalCount, pageIndex, pageSize } = response.data.data;
            logs.value = items;
            pagination.value = {
                page: pageIndex,
                pageSize: pageSize,
                total: totalCount
            };
            return { logs: logs.value, pagination: pagination.value }
        } catch (error) {
            throw new Error(error.message || '搜索日志失败');
        }
    };
    return {
        token,
        logs,
        pagination,
        getLogs,
        searchLogs
    }
})